package com.time.store.order.service;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.time.store.core.util.AuthUtil;
import com.time.store.core.util.NoCardUtil;
import com.time.store.order.entity.bo.OrderInfo;
import com.time.store.order.entity.bo.OrderShipment;
import com.time.store.order.entity.dto.OrderExportShipmentDto;
import com.time.store.order.entity.dto.OrderImportShipmentDto;
import com.time.store.order.entity.dto.OrderShipmentDTO;
import com.time.store.order.entity.dto.OrderShipmentPageReq;
import com.time.store.order.mapper.OrderShipmentMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;


@Service
public class OrderShipmentService extends ServiceImpl<OrderShipmentMapper, OrderShipment> implements IService<OrderShipment> {
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 分页查询订单
     *
     * @param orderShipmentPageReq
     * @return
     */
    public Page<OrderShipment> pageOrderShipment(OrderShipmentPageReq orderShipmentPageReq) {
        Page<OrderShipmentPageReq> page = new Page<>();
        page.setCurrent(orderShipmentPageReq.getCurrent());
        page.setSize(orderShipmentPageReq.getSize());
        return baseMapper.pageOrderShipment(orderShipmentPageReq, page);
    }

    /**
     * 订单单条发货
     */
    public OrderShipment ship(OrderShipmentDTO orderShipmentDto,Integer operationType) {
        OrderShipment orderShipment = new OrderShipment();
        OrderInfo orderInfoBO = orderInfoService.getBaseMapper().selectAllByOrderNo(orderShipmentDto.getOrderNo());

        orderShipment.setOrderNo(orderInfoBO.getOrderNo());
        orderShipment.setShipmentNo(generateShippingCode());
        orderShipment.setOrderId(orderInfoBO.getId());
        orderShipment.setFailReason("");
        orderShipment.setOperatorUserId(AuthUtil.getCurrUserId());
        orderShipment.setOperatorLoginName(AuthUtil.getCurrUserLoginName());
        orderShipment.setTackingNo(orderShipmentDto.getTackingNo());
        orderShipment.setTackingName(orderShipmentDto.getTackingName());
        orderShipment.setOperationType(operationType);
        //TODO 需要动态获取物流公司
        orderShipment.setDeliveryStatus(2);
        orderShipment.setStoreId(AuthUtil.getCurrStoreId());
        BeanUtils.copyProperties(orderShipment, orderShipmentDto);
        baseMapper.insert(orderShipment);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setStatus(3);
        orderInfo.setTackingNo(orderShipmentDto.getTackingNo());
        orderInfo.setId(orderInfo.getId());
        orderInfoService.updateById(orderInfo);
        return orderShipment;
    }


    public String generateShippingCode() {

        String shippingCodeNo = null;
        do {
            shippingCodeNo = NoCardUtil.generateNo("SH");
            // 查询数据库是否已有单号
            Integer shippingCodeNoCount = lambdaQuery().eq(OrderShipment::getShipmentNo, shippingCodeNo).count();
            if (shippingCodeNoCount > 0) {
                shippingCodeNo = null;
            }
        } while (shippingCodeNo == null);


        return shippingCodeNo;
    }

    /**
     * 下载批量发货模板
     */
    public Workbook downBatchTemplate(HttpServletResponse response) throws IOException {
        ExportParams params = new ExportParams();
        String fileName = URLEncoder.encode("订单发货数据", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
        List<OrderExportShipmentDto> orderExportDTOS = new ArrayList<>();
        Workbook workbook = ExcelExportUtil.exportExcel(params, OrderExportShipmentDto.class, orderExportDTOS);
        return workbook;


    }

    /**
     * 发货订单批量导入
     *
     * @param multipartFile
     */
    public void importBatchShipment(MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        List<OrderImportShipmentDto> orderImportShipments = ExcelImportUtil.importExcel(multipartFile.getInputStream(), OrderImportShipmentDto.class, params);
        orderImportShipments.forEach(item -> {
            OrderShipmentDTO orderShipmentDTO = new OrderShipmentDTO();
            BeanUtils.copyProperties(item, orderShipmentDTO);
            ship(orderShipmentDTO,2);
        });
    }
}
